import React, { useCallback, useEffect, useState } from "react";
import SpuInfo from "../IntelligentMatchTable/SpuInfo";
import { useSkuList } from "./useSkuList";
import { useSizeList } from "./useSizeList";
import { SimpleTable } from "@/views/components/SearchTable/index";
import PreviewMatch from "../IntelligentMatchTable/PreviewMatch";
import { Button, message } from "antd";
import Style from "../IntelligentMatchTable/index.module.less";
import { cloneDeep } from "lodash";
import { goodsSpuMatch } from "../service";

import { SupplierSpuMatchModal } from "@/views/components/CommonTableModal";

const Separator = "__@#@__";

const TablePage = props => {
	const { selectedRows, isSkuType, onDrawerClose } = props;
	const selectedRow = selectedRows[0];
	const { spuId, spuImage, spuName } = selectedRow || {};

	const {
		tableKey,
		searchSimpleTableProps,
		handleSupplierSpuModalOk,
		skuList,
		skuSizeList,
		storeSpuSelected,
		storeSpuSelectedAllSku,
		selectOptionsMap,
		dataSource: colorDataSource,
		sizeDataSource,
		setSizeDataSource
	} = useSkuList({
		spuId,
		onDrawerClose,
		Separator
	});

	const { tableKey: sizeTableKey, searchSimpleTableProps: sizeSearchSimpleTableProps } = useSizeList({
		dataSource: sizeDataSource,
		setDataSource: setSizeDataSource,
		Separator,
		skuSizeList,
		colorDataSource,
		selectOptionsMap
	});

	/******************************************** */
	const [previewVisible, setPreviewVisible] = useState(false);
	const [copyMatchData, setCopyMatchData] = useState(false); // 复制【颜色、尺码匹配后的源数据】，用于渲染预览的匹配表格弹窗

	const getMatchData = useCallback(() => {
		const __matchData = [];
		colorDataSource.forEach(colorRow => {
			const { sysColor, storeColor } = colorRow;

			sizeDataSource.forEach(sizeRow => {
				const { sysSpecs } = sizeRow;
				const sysSkuFinder = skuList.find(sysSku => sysSku.specs == sysSpecs && sysSku.colour == sysColor);
				if (sysSkuFinder) {
					const { skuId: sysSkuId, specs: sysSize, skuName: sysSkuName, image: sysSkuImage } = sysSkuFinder;
					Object.keys(sizeRow).forEach(key => {
						if (key.includes(Separator)) {
							const storeSize = sizeRow[key];
							const [storeId, storeSpuId] = key.split(Separator);

							const storeSkuFinder = storeSpuSelectedAllSku.find(
								storeSku =>
									storeSku.storeId == storeId &&
									storeSku.goodsCommonId == storeSpuId &&
									storeSku.color == storeColor &&
									storeSku.size == storeSize
							);
							if (storeSkuFinder) {
								const { goodsId: storeSkuId, goodsImage: storeSkuImage, storeName, goodsName: storeSkuName } = storeSkuFinder;
								__matchData.push({
									sysColor,
									sysSize,
									sysSkuId,
									sysSkuName,
									sysSkuImage,
									////
									storeId,
									storeName,
									storeColor,
									storeSize,
									storeSkuId,
									storeSkuName,
									storeSkuImage
								});
							}
						}
					});
				}
			});
		});
		return __matchData;
	}, [colorDataSource, sizeDataSource]);
	const preview = () => {
		const matchData = getMatchData();

		if (matchData.length == 0) {
			message.warning("未匹配商品");
			return;
		}
		const filterNotSize = matchData.filter(e => e.storeSize);

		if (filterNotSize.length == 0) {
			message.warning("至少匹配一个尺码");
			return;
		}

		setCopyMatchData(cloneDeep(filterNotSize));
		setPreviewVisible(true);
	};

	const onPreviewDelete = (record, index) => {
		setCopyMatchData(pre => {
			if (pre.length > 1) {
				pre.splice(index, 1);
			} else {
				message.warning("至少保留一组匹配关系！");
			}
			return cloneDeep(pre);
		});
	};

	const onPreviewOk = useCallback(() => {
		const API_DATA = {
			ids: [spuId],
			list: copyMatchData.map(record => {
				return {
					// 系统sku
					skuId: record.sysSkuId,
					// 供应商sku
					supplierId: record.storeId,
					supplierName: record.storeName,
					supplierSkuId: record.storeSkuId,
					supplierSkuImage: record.storeSkuImage,
					supplierSkuName: record.storeSkuName
				};
			}),
			type: 2 //关联类型 1：供应商 2：供应商商品
		};

		goodsSpuMatch(API_DATA)
			.then(res => {
				const { success, data, msg } = res;
				if (success) {
					message.success(msg || "匹配成功");
					onPreviewCancel();
					onDrawerClose();
				} else {
					message.warning(msg || "匹配失败");
				}
			})
			.catch(err => {
				console.error(err);
				message.warning("匹配接口请求失败");
			});
	}, [copyMatchData]);

	const onPreviewCancel = () => {
		setPreviewVisible(false);
	};

	return (
		<div className={"views-container " + Style.views_container}>
			<SpuInfo image={spuImage} spuName={spuName}>
				<SupplierSpuMatchModal ids={storeSpuSelected.map(e => e.goodsCommonid)} onOk={handleSupplierSpuModalOk}>
					<Button type="ghost">添加匹配商品</Button>
				</SupplierSpuMatchModal>
			</SpuInfo>

			<SimpleTable key={tableKey} {...searchSimpleTableProps} className={"mb16 " + Style.views_container_table} />

			<SimpleTable key={sizeTableKey} {...sizeSearchSimpleTableProps} className={"mb16 " + Style.views_container_table} />

			<div className={"mb16 " + Style.views_container_button}>
				<Button type="primary" onClick={preview}>
					保存并预览
				</Button>
			</div>

			<PreviewMatch
				visible={previewVisible}
				onCancel={onPreviewCancel}
				onOk={onPreviewOk}
				onDelete={onPreviewDelete}
				dataSource={copyMatchData}
				zIndex={915}
			/>
		</div>
	);
};

export default React.memo(TablePage, () => {
	return true;
});
